package com.hm.ibsm.util;

import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.hm.common.util.EncryptUtil;
import com.hm.common.util.EncryptUtil.Base64;
import com.hm.common.util.UriUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author shishun.wang
 * @date 2017年3月12日 下午8:59:09
 * @version 1.0
 * @describe
 */
public abstract class BaseController {

	protected String SESSION_TIME_OUT_URL = "redirect:/index.do?error=true&result=" + UriUtil.encode(new String(Base64.encode("会话超时,请重新登录".getBytes())));

	protected ModelAndView sessionTimeOut() {
		return new ModelAndView(SESSION_TIME_OUT_URL);
	}

	@RequestMapping(value = { "", "/", "/index.do" })
	public String index(ModelMap model, @RequestParam(name = "error", required = false) boolean error,
			@RequestParam(name = "result", required = false) String result) {
		if (error) {
			model.addAttribute("errorMsg", new String(EncryptUtil.Base64.decode(result.toCharArray())));
		}
		return "index";
	}

	protected void putHtml(String data) {
		try {
			HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-type", "text/html;charset=UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().print(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected String json(Object obj) {
		try {
			return JSONObject.fromObject(obj).toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	protected void putJson(Object obj) {
		try {
			HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json");
			response.getWriter().print(JSONObject.fromObject(obj));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void putJsonArray(Object obj) {
		try {
			HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.getWriter().print(JSONArray.fromObject(obj));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
